package logic

import (
	"context"
	"database/sql"
	"errors"
	"shorturl/internal/svc"
	"shorturl/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShowLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewShowLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShowLogic {
	return &ShowLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ShowLogic) Show(req *types.ShowRequest) (resp *types.ShowResponse, err error) {
	exists, err := l.svcCtx.Filter.Exists([]byte(req.ShortURL))
	if err != nil {
		logx.Errorw("Bloom Exists failed", logx.LogField{Key: "err", Value: err.Error()})
	}
	if !exists {
		return nil, errors.New("404")
	}
	// 将生成的短链接加到布隆过滤器中
	if err := l.svcCtx.Filter.Add([]byte(req.ShortURL)); err != nil {
		logx.Errorw("Bloom Add failed", logx.LogField{Key: "err", Value: err.Error()})
		return nil, err
	}
	// 查看短链接重定向到定向的长链接
	url, err := l.svcCtx.ShortUrlMapModel.FindOneBySurl(l.ctx, sql.NullString{Valid: true, String: req.ShortURL})
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, errors.New("404")
		}
		logx.Errorw("ShortUrlMapModel.FindOneBySurl Failed", logx.LogField{Key: "err", Value: err.Error()})
		return nil, err
	}
	// 返回查询到的长链接
	return &types.ShowResponse{LongURL: url.Lurl.String}, nil
}
